 //
//  HDAppDelegate.m
//  healthyexpert
//
//  Created by Liu Penny on 15-1-14.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDAppDelegate.h"
#import "Tool.h"        //上个版本的万能工具类
#import "SNPleaseLogInAlertView.h"
#import "JKReporter.h"

#import "HZUnCatchExceptionHandler.h"

#import "HZCachingURLProtocol.h"
#import "HZCachingURLCache.h"
#import "SDURLCache.h"
#import "HDChatFmdbManager.h"
#import "HZGoodsSalesViewController.h"
#import "HDChatLIstController.h"
#import "HZGoodsDetailViewController.h"
#import "HDUserInforHttpRequestManger.h"
#import "HDChatProductResult.h"
#import "HDChatOBOManager.h"
#import "HDChatListManager.h"
#import "HZMallGoodsListViewController.h"
#import "HZMallGoodsTemaiListViewController.h"
#import "SNSystemNotifyController.h"
#import "ParticipationViewController.h"
//支付宝
#import <AlipaySDK/AlipaySDK.h>


#import "SNSessionManager.h"

#import "HDLockManger.h"

@interface HDAppDelegate ()<UIAlertViewDelegate>

@property (nonatomic, strong) HDChatFmdbManager * chatFmdbManger;
@property (nonatomic, strong) HDChatProductResult * productResult;
@property (nonatomic, strong) NSMutableArray * tempPmid;
@property (nonatomic, strong) NSDictionary * dict;
@property (nonatomic, strong) JKRemoteResult * signIn;
@property (nonatomic, strong) HDChatOBOManager * chatOBOManager;
@property (nonatomic, strong) HDChatListManager * chatListManager;
@property (nonatomic,strong) AFNetworkReachabilityManager *reachManager;



@end

@implementation HDAppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
@synthesize storyBoard = _storyBoard;
//@synthesize database = _database;
@synthesize location = _location;
@synthesize gt_appKey = _gt_appKey;
@synthesize gt_appSecret = _gt_appSecret;
@synthesize gt_appID = _gt_appID;
@synthesize clientId = _clientId;
@synthesize sdkStatus = _sdkStatus;
@synthesize lastPayloadIndex = _lastPaylodIndex;
@synthesize payloadId = _payloadId;

#pragma mark - 注册APNS
- (void)registerRemoteNotification
{

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        
        UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:uns];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    /** 用户点击通知启动app的时候调用此方法 -write by khzliu */
    NSDictionary * userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if(userInfo && userInfo.count > 0){
    
        //分析推送过来的消息并处理
        [self analysisRemoteNotification:userInfo];
    }
    
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    if ([ud objectForKey:@"uid"]) {
        [SNSessionManager reloadSessionId];
    }
    
    SDURLCache *cache = [[SDURLCache alloc] initWithMemoryCapacity:10*1024*1024 diskCapacity:20*1024*1024 diskPath:[NSString stringWithFormat:@"%@/%@", [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject], kMallFileLocalWebCacheFolder]];
    [NSURLCache setSharedURLCache:cache];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//    self.loginViewController = [[HDLoginoutViewController alloc]init];
    self.tempPmid = [NSMutableArray array];
    self.state = YES;
    self.chatFmdbManger = [HDChatFmdbManager shareManager];
    self.chatListManager = [HDChatListManager shareManager];
    self.chatOBOManager = [HDChatOBOManager shareManager];
    self.productResult = [[HDChatProductResult alloc]initWithTarget:self action:@selector(getShopContent:)];
    self.uniteUrl = [SNUniteUrl shareUniteUrl];
    
    
    
    //开启网络状态监听
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    #pragma mark - 初始化 FMDB 数据库队列
    self.fmdbQueue = [FMDatabaseQueue databaseQueueWithPath:kDBPath];
    DLog(@"%@",kDBPath);
//    [self loadSqlite];
    
    //setup EmojiStrings;加载表情到内存
    [self setupEmojiToMemory];
    
    [WXApi registerApp:WX_APP_ID];

    // [1]:使用APPID/APPKEY/APPSECRENT创建个推实例
    [self startSdkWith:GT_APP_ID appKey:GT_APP_KEY appSecret:GT_APP_SECRET];
    
    // [2]:注册APNS
    [self registerRemoteNotification];
    
    // [2-EXT]: 获取启动时收到的APN
    NSDictionary* message = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (message) {
        NSString *payloadMsg = [message objectForKey:@"payload"];
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], payloadMsg];
        NSLog(@"record = %@",record);
        
    }
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    
    [[MTAConfig getInstance] setDebugEnable:TRUE];
    [MTA startWithAppkey:MTA_APPKEY];
    [[MTAConfig getInstance] setChannel:@"appstore"];
    [[MTAConfig getInstance] setReportStrategy: MTA_STRATEGY_PERIOD];
    [[MTAConfig getInstance] setSessionTimeoutSecs:30];
//
    //    [MTA trackException:];
    
    //catch uncatched exception
    InstallUncaughtExceptionHandler();
    
    //cache NSURLConnection NSURLRequest data
    //[NSURLProtocol registerClass:[HZCachingURLProtocol class]];
    
    
    //更新秘钥
    [self  updataMIyao];
    

    //    其他sdk 内置启动mta
    //    ........
    
//    上报行为记录
    
    if ([CLLocationManager locationServicesEnabled]) {
        self.location = [[CLLocationManager alloc]init];
        self.location.delegate = self;
        if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        {
            [self.location requestAlwaysAuthorization];
        }
        self.location.desiredAccuracy = kCLLocationAccuracyBest;
        self.location.distanceFilter = kCLDistanceFilterNone;
        [self.location startUpdatingLocation];
    }
    
//    启动方式
    self.pushInfoArray = [NSMutableArray arrayWithCapacity:1];
    self.pushInfo = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    
    
    // 全局设置 navigationbar
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -180) forBarMetrics:UIBarMetricsDefault];
    UIImage *backButtonImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ic_actionbar_home_up@2x.png" ofType:nil]];
    [[UINavigationBar appearance] setBackIndicatorImage:backButtonImage];
//    [[UIBarButtonItem appearance] setTintColor:[XCommon hexStringToColor:kColor_00C45C]];
    
    
    //    方法1: IOS7 的新方法，图片要和系统原生的一样大
//    [[UINavigationBar appearance] setBackIndicatorImage:backButtonImage];
//    [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:backButtonImage];
//    [[UINavigationBar appearance] setTintColor:[XCommon hexStringToColor:kColor_green_item]];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: [XCommon hexStringToColor:kColor_red_text],NSForegroundColorAttributeName,[UIFont boldSystemFontOfSize:17],NSFontAttributeName,nil];
    [[UINavigationBar appearance] setTitleTextAttributes:dict];
    //[[UINavigationBar appearance] setBackgroundColor:HZ_WHITE_COLOR];
    //[UINavigationBar appearance].translucent = YES;
    
    //设置UITabar的item的title设置为透明色
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor clearColor], NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    
    
//        方法2: 替换背景图，图片要宽一个像素
        int imageSize = 25;
        [[UIBarButtonItem appearance] setBackButtonBackgroundImage:[backButtonImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, imageSize, 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    
//    if(![[NSUserDefaults standardUserDefaults]boolForKey:@"firstLaunch"])
//    {
//        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"firstLaunch"];
//        
//        self.storyBoard = [UIStoryboard storyboardWithName:@"IntroduceStoryboard" bundle:nil];
//        
//        UIPageControl *pageControl = [UIPageControl appearance];
//        pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
//        pageControl.currentPageIndicatorTintColor = [UIColor blackColor];
//        pageControl.backgroundColor = [UIColor whiteColor];
//        
//        self.window.rootViewController = [self.storyBoard instantiateInitialViewController];
//    }
//    else
    {
        [[UIApplication sharedApplication] setStatusBarHidden:NO];
        
        if([[NSUserDefaults standardUserDefaults]boolForKey:@"login"])
        {
            //    上报行为记录
            [self berichten: @"HDAppDelegate"];
#warning - 下面这行代码被SN注释了,记得改回来
//            [self updateUserInfo];
            self.storyBoard = [UIStoryboard storyboardWithName:@"MainStoryBoard" bundle:nil];
            self.window.rootViewController = [self.storyBoard instantiateInitialViewController];
            
            self.window.backgroundColor = HZ_WHITE_COLOR;
        }
        else
        {
            self.storyBoard = [UIStoryboard storyboardWithName:@"MainStoryBoard" bundle:nil];
            self.window.rootViewController = [self.storyBoard instantiateInitialViewController];
            self.window.backgroundColor = HZ_WHITE_COLOR;

        }
//        {
//            self.storyBoard = [UIStoryboard storyboardWithName:@"LogInOutStoryboard" bundle:nil];
//            self.window.rootViewController = [self.storyBoard instantiateInitialViewController];
//    
//        }
    }


    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(teMaiActivity:) name:@"System" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentView:) name:@"presentView" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(presentChatListView:) name:@"ChatList" object:nil];
    
    
   [[self window] makeKeyAndVisible];
    
    return YES;
}

#pragma mark 更新baseURL 失败
- (void)updateBaseURLFailure:(NSNotification *)notice
{
    
    [self performSelector:@selector(updateBaseURL) withObject:nil afterDelay:1.0f];
    
}

#pragma mark - 通知跳转

#pragma mark - 跳转到系统
-(void)teMaiActivity:(NSNotification*)info
{
    NSDictionary *pmidDictionary = [info userInfo];
    ParticipationViewController * systemNotifyVC = [[ParticipationViewController alloc] init];
    systemNotifyVC.APNSKey = YES;
    systemNotifyVC.hidesBottomBarWhenPushed = YES;
    UIViewController * vc =self.window.rootViewController;
    
    if ([vc isKindOfClass:UITabBarController.class]) {
        
        UITabBarController * tabarVc  = (UITabBarController*)vc;
        tabarVc.selectedIndex = 1;
        
//        vc = ((UITabBarController*)vc).selectedViewController;
//        if ([vc isKindOfClass:UINavigationController.class]) {
//            [(UINavigationController*)vc pushViewController:systemNotifyVC animated:YES ];
//        }
    }
    else
    {
        if (pmidDictionary != nil) {
            [[NSUserDefaults standardUserDefaults] setObject:@"temaidata" forKey:@"kRemoteNotificationUserInfoType"];
            [[NSUserDefaults standardUserDefaults] setObject:pmidDictionary forKey:@"kRemoteNotificationUserInfoData"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
        
    }

    
    
    
}

#pragma mark -跳转到活动
-(void)activity:(NSNotification*)info
{
    NSDictionary *pmidDictionary = [info userInfo];
    
    HZMallGoodsListViewController *mallGoodsListVC = [[HZMallGoodsListViewController alloc] init];
    mallGoodsListVC.actID = [pmidDictionary objectForKey:@"actid"];
    mallGoodsListVC.actName = [pmidDictionary objectForKey:@"actname"];
    mallGoodsListVC.hidesBottomBarWhenPushed = YES;
    UIViewController * vc =self.window.rootViewController;
    if ([vc isKindOfClass:UITabBarController.class]) {
        
        vc = ((UITabBarController*)vc).selectedViewController;
        if ([vc isKindOfClass:UINavigationController.class]) {
            [(UINavigationController*)vc pushViewController:mallGoodsListVC animated:YES ];
        }
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setObject:@"activitydata" forKey:@"kRemoteNotificationUserInfoType"];
        [[NSUserDefaults standardUserDefaults] setObject:pmidDictionary forKey:@"kRemoteNotificationUserInfoData"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    
}

#pragma makr -  跳转到web
-(void)presentView:(NSNotification*)info
{
    NSDictionary *pmidDictionary = [info userInfo];
    HZGoodsSalesViewController *salesVC = [[HZGoodsSalesViewController alloc] init];
    salesVC.webTitle = [pmidDictionary objectForKey:@"title"];
    salesVC.webURL = [NSString stringWithFormat:@"%@uid=%@",[pmidDictionary objectForKey:@"url"],[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
    salesVC.hidesBottomBarWhenPushed = YES;
    UIViewController * vc =self.window.rootViewController;
    if ([vc isKindOfClass:UITabBarController.class]) {
        
        vc = ((UITabBarController*)vc).selectedViewController;
        if ([vc isKindOfClass:UINavigationController.class]) {
            [(UINavigationController*)vc pushViewController:salesVC animated:YES ];
        }
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setObject:@"webdata" forKey:@"kRemoteNotificationUserInfoType"];
        [[NSUserDefaults standardUserDefaults] setObject:pmidDictionary forKey:@"kRemoteNotificationUserInfoData"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

}

#pragma mark - 跳转到聊天列表
-(void)presentChatListView:(NSNotification*)info
{
    NSDictionary *pmidDictionary = [info userInfo];
    HDChatLIstController * chatList = [[HDChatLIstController alloc]init];
    chatList.tempPmids = [pmidDictionary objectForKey:@"pmid"];
    chatList.chatSign = @"0";
    chatList.hidesBottomBarWhenPushed = YES;
    UIViewController * vc =self.window.rootViewController;
    if ([vc isKindOfClass:UITabBarController.class]) {
        
        vc = ((UITabBarController*)vc).selectedViewController;
        if ([vc isKindOfClass:UINavigationController.class]) {
            [(UINavigationController*)vc pushViewController:chatList animated:YES ];
        }

    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setObject:@"chatlistdata" forKey:@"kRemoteNotificationUserInfoType"];
        [[NSUserDefaults standardUserDefaults] setObject:pmidDictionary forKey:@"kRemoteNotificationUserInfoData"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
}
#pragma mark - 跳转到商品详情
-(void)presentCardView:(NSNotification*)info
{
    
    NSDictionary *pmidDictionary = [info userInfo];
    HZGoodsDetailViewController *detailVC = [[HZGoodsDetailViewController alloc] init];
    detailVC.shopID = [pmidDictionary objectForKey:@"shopid"];
    detailVC.productID = [pmidDictionary objectForKey:@"productid"];
    detailVC.hidesBottomBarWhenPushed = YES;
    UIViewController * vc =self.window.rootViewController;
    if ([vc isKindOfClass:UITabBarController.class]) {
        
        vc = ((UITabBarController*)vc).selectedViewController;
        if ([vc isKindOfClass:UINavigationController.class]) {
            [(UINavigationController*)vc pushViewController:detailVC animated:YES ];
        }
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setObject:@"carddata" forKey:@"kRemoteNotificationUserInfoType"];
        [[NSUserDefaults standardUserDefaults] setObject:pmidDictionary forKey:@"kRemoteNotificationUserInfoData"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    
    
    
    
}


-(void)updataMIyao
{
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"lock_phone"]length] > 0) {
        
        HDLockManger * manger = [HDLockManger shareManager];
        
        HDMiyaoRequset * miyao_reqeust = [[HDMiyaoRequset alloc]initWithTarget:self action:@selector(updataMiyaoResult:)];
        
        
        NSDictionary * params = @{@"phone":[[NSUserDefaults standardUserDefaults]objectForKey:@"lock_phone"]};
        
        [manger getMIyaoRequest:miyao_reqeust Params:params];
        
        
    }
    
    

}

-(void)updataMiyaoResult:(HDMiyaoRequset*)rt
{
    if (rt.success) {
//        [MyToast showWithText:rt.msg];
        
        //获取二维码
        DLog(@"更新成功");
        NSArray * array = [rt.pushDic arrayForKey:@"result"];
        if (array.count > 0) {
            
            NSMutableArray * temp_array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults]objectForKey:@"erweima_key"]];
            
            if (temp_array.count > 0) {
                [temp_array removeAllObjects];
            }
            
            for (int i = 0 ; i < array.count; i++) {
                NSDictionary * temp = [array objectAtIndex:i];
                NSString * key = [temp objectForKey:@"key"];
                [temp_array addObject:key];
                
            }
            

            [[NSUserDefaults standardUserDefaults]setObject:temp_array forKey:@"erweima_key"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            

            
        }else
        {
            //            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [MyToast showDefaultBottonWithText:@"电话号码未授权"];
        }
        
        
        
        
    }
    else if (rt.status == 1){
        //清除key 和令令id
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"erweima_key"];
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"linglingID"];
    
    }
    else
    {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        [MyToast showWithText:rt.msg];
        
    }
}


////////////////////////////////************个推
#pragma  mark - 创建个推实例
- (void)startSdkWith:(NSString *)appID appKey:(NSString *)appKey appSecret:(NSString *)appSecret
{
    if (!_gexinPusher) {
        _sdkStatus = SdkStatusStoped;
        
        self.gt_appID = appID;
        self.gt_appKey = appKey;
        self.gt_appSecret = appSecret;
        
        _clientId = nil;
        
        NSError *err = nil;
        _gexinPusher = [GexinSdk createSdkWithAppId:_gt_appID
                                             appKey:_gt_appKey
                                          appSecret:_gt_appSecret
                                         appVersion:@"0.0.0"
                                           delegate:self
                                              error:&err];
        if (!_gexinPusher) {
            //            [_viewController logMsg:[NSString stringWithFormat:@"%@", [err localizedDescription]]];
        } else {
            _sdkStatus = SdkStatusStarting;
        }
        
        //        [_viewController updateStatusView:self];
    }
    
}
#pragma mark - 个推停止
- (void)stopSdk
{
    if (_gexinPusher) {
        [_gexinPusher destroy];
        _gexinPusher = nil;
        
        _sdkStatus = SdkStatusStoped;
        _clientId = nil;
        
        //        [_viewController updateStatusView:self];
    }
}
- (BOOL)checkSdkInstance
{
    if (!_gexinPusher) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误" message:@"SDK未启动" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        //        [alertView show];
        return NO;
    }
    return YES;
}
- (void)setDeviceToken:(NSString *)aToken
{
    if (![self checkSdkInstance]) {
        return;
    }
    
    [_gexinPusher registerDeviceToken:aToken];
}

- (BOOL)setTags:(NSArray *)aTags error:(NSError **)error
{
    if (![self checkSdkInstance]) {
        return NO;
    }
    
    return [_gexinPusher setTags:aTags];
}


- (NSString *)sendMessage:(NSData *)body error:(NSError **)error {
    if (![self checkSdkInstance]) {
        return nil;
    }
    
    return [_gexinPusher sendMessage:body error:error];
}

- (void)bindAlias:(NSString *)aAlias {
    if (![self checkSdkInstance]) {
        return;
    }
    
    return [_gexinPusher bindAlias:aAlias];
}

- (void)unbindAlias:(NSString *)aAlias {
    if (![self checkSdkInstance]) {
        return;
    }
    
    return [_gexinPusher unbindAlias:aAlias];
}
#pragma mark - GexinSdkDelegate
- (void)GexinSdkDidRegisterClient:(NSString *)clientId
{
    // [4-EXT-1]: 个推SDK已注册
    _sdkStatus = SdkStatusStarted;
    _clientId = clientId;
    NSLog(@"clientID = %@",clientId);
    
    NSString* urlStr = [NSString stringWithFormat:@"%@?clientid=%@&uid=%@",self.uniteUrl.per_upLoadGePushIdUrl,clientId,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
    DLog(@"%@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *strJson = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
    
    
    //    [_viewController updateStatusView:self];
    
    //      [self stopSdk];
}
static int state = 0;
- (void)GexinSdkDidReceivePayload:(NSString *)payloadId fromApplication:(NSString *)appId
{
    //  收到个推消息
    _payloadId = payloadId;
    NSData *payload = [_gexinPusher retrivePayloadById:payloadId];
    NSString *payloadMsg = nil;
    if (payload) {
        payloadMsg = [[NSString alloc] initWithBytes:payload.bytes
                                              length:payload.length
                                            encoding:NSUTF8StringEncoding];
    }
    NSLog(@"Msg = %@",payloadMsg);
    NSData *jsonData = [payloadMsg dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * pushDic = [jsonData objectFromJSONData];
    
    
    //私信消息模式
    if ([[[pushDic objectForKey:@"custom"]objectForKey:@"tp"]integerValue] > 10) {
        //增加小红点
        NSString * reply = [NSString stringWithFormat:@"reply%@",[[pushDic objectForKey:@"custom"]objectForKey:@"u"]];
        
        if ([[[pushDic objectForKey:@"custom"]objectForKey:@"tp"]integerValue] == 20) {
            //聊天消息
            if ([self.chatFmdbManger fmdbIncludeChatList] && [self.chatFmdbManger fmdbIncludeData]) {
                //有表有数据
                
                if ([self.chatFmdbManger isRepeatFromFmdbWithPmid:[[pushDic objectForKey:@"custom"]objectForKey:@"m"] Msgid:[[pushDic objectForKey:@"custom"]objectForKey:@"i"]] == 1){
                    //无遗漏消息 更新
                    NSDictionary * dict = @{@"m":[[pushDic objectForKey:@"custom"]objectForKey:@"m"],
                                            @"n":[[pushDic objectForKey:@"custom"]objectForKey:@"n"],
                                            @"f":[[pushDic objectForKey:@"custom"]objectForKey:@"f"],
                                            @"c":[[pushDic objectForKey:@"custom"]objectForKey:@"c"],
                                            @"d":[[pushDic objectForKey:@"custom"]objectForKey:@"d"],
                                            @"u":[[pushDic objectForKey:@"custom"]objectForKey:@"u"],
                                            @"i":[[pushDic objectForKey:@"custom"]objectForKey:@"i"],
                                            @"sign":@"0",
                                            @"delSign":@"000"};
                    [self.chatFmdbManger updata:dict];
                    
                }else if ([self.chatFmdbManger isRepeatFromFmdbWithPmid:[[pushDic objectForKey:@"custom"]objectForKey:@"m"] Msgid:[[pushDic objectForKey:@"custom"]objectForKey:@"i"]] == 2){
                    // 有遗漏消息 更新
                    
                    NSDictionary * dict = @{@"m":[[pushDic objectForKey:@"custom"]objectForKey:@"m"],
                                            @"n":[[pushDic objectForKey:@"custom"]objectForKey:@"n"],
                                            @"f":[[pushDic objectForKey:@"custom"]objectForKey:@"f"],
                                            @"c":[[pushDic objectForKey:@"custom"]objectForKey:@"c"],
                                            @"d":[[pushDic objectForKey:@"custom"]objectForKey:@"d"],
                                            @"u":[[pushDic objectForKey:@"custom"]objectForKey:@"u"],
                                            @"i":[[pushDic objectForKey:@"custom"]objectForKey:@"i"],
                                            @"sign":@"1",
                                            @"delSign":@"000"};
                    [self.chatFmdbManger updata:dict];
                    
                }else if ([self.chatFmdbManger isRepeatFromFmdbWithPmid:[[pushDic objectForKey:@"custom"]objectForKey:@"m"] Msgid:[[pushDic objectForKey:@"custom"]objectForKey:@"i"]] == 3){
                    //插入新消息
                    
                    NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatListManager arrayFromFmdb]count]];
                    
                    NSArray * dataArray = @[[[pushDic objectForKey:@"custom"]objectForKey:@"u"],[[pushDic objectForKey:@"custom"]objectForKey:@"m"],[[pushDic objectForKey:@"custom"]objectForKey:@"n"],[[pushDic objectForKey:@"custom"]objectForKey:@"f"],[[pushDic objectForKey:@"custom"]objectForKey:@"c"],[[pushDic objectForKey:@"custom"]objectForKey:@"d"],ownerAddId,[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"0",[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"000"];
                    [self.chatFmdbManger saveDataToDB:dataArray OwnerAddId:ownerAddId];
                    
                }
                else
                {
                    //丢弃不保存；
                }

                
 
            }
            else if(![self.chatFmdbManger fmdbIncludeChatList] || ![self.chatFmdbManger fmdbIncludeData])
            {
                //无表或无数据
                [self.chatFmdbManger createFmdb];
                
                NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatListManager arrayFromFmdb]count]];
                
                 NSArray * dataArray = @[[[pushDic objectForKey:@"custom"]objectForKey:@"u"],[[pushDic objectForKey:@"custom"]objectForKey:@"m"],[[pushDic objectForKey:@"custom"]objectForKey:@"n"],[[pushDic objectForKey:@"custom"]objectForKey:@"f"],[[pushDic objectForKey:@"custom"]objectForKey:@"c"],[[pushDic objectForKey:@"custom"]objectForKey:@"d"],ownerAddId,[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"0",[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"000"];
                [self.chatFmdbManger saveDataToDB:dataArray OwnerAddId:ownerAddId];
 
 
            }
            
            
            if ([self.chatOBOManager fmdbIncludeChatPeople:[[pushDic objectForKey:@"custom"] objectForKey:@"u"]] && [self.chatOBOManager fmdbInculdeContentDataWithPeople:[[pushDic objectForKey:@"custom"] objectForKey:@"u"]]) {
                //聊天详情表 有表有数据
#pragma mark - 康喜汇独特聊天
                //插入到聊天详情表
                if ([[[pushDic objectForKey:@"custom"]objectForKey:@"mtype"]integerValue] == 3) {
                    //商品信息
                    [self.chatFmdbManger loadShopContent:self.productResult Extends:pushDic Product:[[pushDic objectForKey:@"custom"]objectForKey:@"product_id"]];
                }else
                {
                    if ([[[pushDic objectForKey:@"custom"]objectForKey:@"p"]length] > 0) {
                        //有图片的信息
                        
                        NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatOBOManager arrayFromFmdbWithPmid:[[pushDic objectForKey:@"custom"]objectForKey:@"u"]]count]];
                        
                         NSArray * dataArray = @[ownerAddId,[[pushDic objectForKey:@"custom"]objectForKey:@"d"],[[pushDic objectForKey:@"custom"]objectForKey:@"c"],[pushDic objectForKey:@"receiver_uid"],[[pushDic objectForKey:@"custom"]objectForKey:@"u"],[[pushDic objectForKey:@"custom"]objectForKey:@"i"],[[pushDic objectForKey:@"custom"]objectForKey:@"l"],[[pushDic objectForKey:@"custom"]objectForKey:@"p"],@"0",[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"2",@"2",@"0",@"",@""];
                        
                        //                        [self.chatOBOManager saveDatetoDBWithPeople:[[pushDic objectForKey:@"custom"]objectForKey:@"u"] Array:dataArray];
                        
                        [self.chatFmdbManger saveDataToDbPeople:dataArray People:[[pushDic objectForKey:@"custom"]objectForKey:@"u"]];
                    }else
                    {
                        //无图片的信息
                        
                        NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatOBOManager arrayFromFmdbWithPmid:[[pushDic objectForKey:@"custom"]objectForKey:@"u"]]count]];
                        
                         NSArray * dataArray = @[ownerAddId,[[pushDic objectForKey:@"custom"]objectForKey:@"d"],[[pushDic objectForKey:@"custom"]objectForKey:@"c"],[pushDic objectForKey:@"receiver_uid"],[[pushDic objectForKey:@"custom"]objectForKey:@"u"],[[pushDic objectForKey:@"custom"]objectForKey:@"i"],[[pushDic objectForKey:@"custom"]objectForKey:@"l"],[[pushDic objectForKey:@"custom"]objectForKey:@"p"],@"0",[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"1",@"1",@"0",@"",@""];
                        
                        [self.chatFmdbManger saveDataToDbPeople:dataArray People:[[pushDic objectForKey:@"custom"]objectForKey:@"u"]];
                    }
                    
                }
                
                
            }else
            {
                
                //聊天详情表 无表无数据
                [self.chatFmdbManger createTableWithPeople:[[pushDic objectForKey:@"custom"]objectForKey:@"u"]];
                
#pragma mark - 康喜汇独特聊天
                //插入到聊天详情表
                if ([[[pushDic objectForKey:@"custom"]objectForKey:@"mtype"]integerValue] == 3) {
                    //商品信息
                    [self.chatFmdbManger loadShopContent:self.productResult Extends:pushDic Product:[[pushDic objectForKey:@"custom"]objectForKey:@"product_id"]];
                }else
                {
                    if ([[[pushDic objectForKey:@"custom"]objectForKey:@"p"]length] > 0) {
                        //有图片的信息
                        NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatOBOManager arrayFromFmdbWithPmid:[[pushDic objectForKey:@"custom"]objectForKey:@"u"]]count]];
                        
                       NSArray * dataArray = @[ownerAddId,[[pushDic objectForKey:@"custom"]objectForKey:@"d"],[[pushDic objectForKey:@"custom"]objectForKey:@"c"],[pushDic objectForKey:@"receiver_uid"],[[pushDic objectForKey:@"custom"]objectForKey:@"u"],[[pushDic objectForKey:@"custom"]objectForKey:@"i"],[[pushDic objectForKey:@"custom"]objectForKey:@"l"],[[pushDic objectForKey:@"custom"]objectForKey:@"p"],@"0",[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"2",@"2",@"0",@"",@""];
                        [self.chatFmdbManger saveDataToDbPeople:dataArray People:[[pushDic objectForKey:@"custom"]objectForKey:@"u"]];
                    }else
                    {
                        //无图片的信息
                        NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatOBOManager arrayFromFmdbWithPmid:[[pushDic objectForKey:@"custom"]objectForKey:@"u"]]count]];
                        
                         NSArray * dataArray = @[ownerAddId,[[pushDic objectForKey:@"custom"]objectForKey:@"d"],[[pushDic objectForKey:@"custom"]objectForKey:@"c"],[pushDic objectForKey:@"receiver_uid"],[[pushDic objectForKey:@"custom"]objectForKey:@"u"],[[pushDic objectForKey:@"custom"]objectForKey:@"i"],[[pushDic objectForKey:@"custom"]objectForKey:@"l"],[[pushDic objectForKey:@"custom"]objectForKey:@"p"],@"0",[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"1",@"1",@"0",@"",@""];
                        
                        [self.chatFmdbManger saveDataToDbPeople:dataArray People:[[pushDic objectForKey:@"custom"]objectForKey:@"u"]];
                    }
                    
                }
                
                
            }
            
            
        }
        else if ([[[pushDic objectForKey:@"custom"]objectForKey:@"tp"]integerValue] == 12) {
            if ([self.chatFmdbManger fmdbIncludeChatList] && [self.chatFmdbManger fmdbIncludeData]) {
                //回复有表有数据
                
                if ([self.chatFmdbManger isRepeatFromFmdbWithPmid:reply Msgid:[[pushDic objectForKey:@"custom"]objectForKey:@"i"]] == 1){
                    //无遗漏消息 更新
                    
                    NSDictionary * dict = @{@"m":reply,
                                            @"n":[[pushDic objectForKey:@"custom"]objectForKey:@"n"],
                                            @"f":[[pushDic objectForKey:@"custom"]objectForKey:@"f"],
                                            @"c":[[pushDic objectForKey:@"custom"]objectForKey:@"c"],
                                            @"d":[[pushDic objectForKey:@"custom"]objectForKey:@"d"],
                                            @"u":[[pushDic objectForKey:@"custom"]objectForKey:@"u"],
                                            @"i":[[pushDic objectForKey:@"custom"]objectForKey:@"i"],
                                            @"sign":@"0"};
                    [self.chatFmdbManger updata:dict];
                    
                }else if ([self.chatFmdbManger isRepeatFromFmdbWithPmid:reply Msgid:[[pushDic objectForKey:@"custom"]objectForKey:@"i"]] == 2){
                    // 有遗漏消息 更新
                    
                    NSDictionary * dict = @{@"m":reply,
                                            @"n":[[pushDic objectForKey:@"custom"]objectForKey:@"n"],
                                            @"f":[[pushDic objectForKey:@"custom"]objectForKey:@"f"],
                                            @"c":[[pushDic objectForKey:@"custom"]objectForKey:@"c"],
                                            @"d":[[pushDic objectForKey:@"custom"]objectForKey:@"d"],
                                            @"u":[[pushDic objectForKey:@"custom"]objectForKey:@"u"],
                                            @"i":[[pushDic objectForKey:@"custom"]objectForKey:@"i"],
                                            @"sign":@"1"};
                    [self.chatFmdbManger updata:dict];
                    
                }else if ([self.chatFmdbManger isRepeatFromFmdbWithPmid:reply Msgid:[[pushDic objectForKey:@"custom"]objectForKey:@"i"]] == 3){
                    //插入新消息
                    
                     NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatListManager arrayFromFmdb]count]];
                    NSArray * dataArray = @[reply,[[pushDic objectForKey:@"custom"]objectForKey:@"m"],[[pushDic objectForKey:@"custom"]objectForKey:@"n"],[[pushDic objectForKey:@"custom"]objectForKey:@"f"],[[pushDic objectForKey:@"custom"]objectForKey:@"c"],[[pushDic objectForKey:@"custom"]objectForKey:@"d"],ownerAddId,[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"0",[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"000"];
                    [self.chatFmdbManger saveDataToDB:dataArray OwnerAddId:ownerAddId];
                    
                }
                else
                {
                    //丢弃不保存；
                }
            }else
            {
                //无表或无数据
                [self.chatFmdbManger createFmdb];
                 NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatListManager arrayFromFmdb]count]];
                
                NSString * reply = [NSString stringWithFormat:@"reply%@",[[pushDic objectForKey:@"custom"]objectForKey:@"u"]];
                
                NSArray * dataArray = @[reply,[[pushDic objectForKey:@"custom"]objectForKey:@"m"],[[pushDic objectForKey:@"custom"]objectForKey:@"n"],[[pushDic objectForKey:@"custom"]objectForKey:@"f"],[[pushDic objectForKey:@"custom"]objectForKey:@"c"],[[pushDic objectForKey:@"custom"]objectForKey:@"d"],ownerAddId,[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"0",[[pushDic objectForKey:@"custom"]objectForKey:@"i"],@"000"];
                [self.chatFmdbManger saveDataToDB:dataArray OwnerAddId:ownerAddId];
            }
            
            //插入回帖数据库
            
            NSArray * array = @[[[pushDic objectForKey:@"custom"]objectForKey:@"i"],[[pushDic objectForKey:@"custom"]objectForKey:@"tl"],[[pushDic objectForKey:@"custom"]objectForKey:@"u"],[[pushDic objectForKey:@"custom"]objectForKey:@"b"],[[pushDic objectForKey:@"custom"]objectForKey:@"t"],[[pushDic objectForKey:@"custom"]objectForKey:@"c"],[[pushDic objectForKey:@"custom"]objectForKey:@"f"],[[pushDic objectForKey:@"custom"]objectForKey:@"n"],[[pushDic objectForKey:@"custom"]objectForKey:@"d"],@"0",[[pushDic objectForKey:@"custom"]objectForKey:@"i"]];
            [self.chatFmdbManger saveToChatReplyDb:array];
            
        }
        
        
        if ([[[pushDic objectForKey:@"custom"]objectForKey:@"tp"]integerValue] != 15) {
            
            
            if (self.tempPmid.count != 0) {
                for (int i = 0 ; i < self.tempPmid.count; i++) {
                    if (![[[pushDic objectForKey:@"custom"]objectForKey:@"m"] isEqualToString:[self.tempPmid objectAtIndex:i]]) {
                        if ([[[pushDic objectForKey:@"custom"]objectForKey:@"m"]integerValue] != 0) {
                            [self.tempPmid addObject:[[pushDic objectForKey:@"custom"]objectForKey:@"m"]];
                        }else
                        {
                            [self.tempPmid addObject:reply];
                        }
                        
                    }
                }
            }else
            {
                if ([[[pushDic objectForKey:@"custom"]objectForKey:@"m"]integerValue] != 0) {
                    [self.tempPmid addObject:[[pushDic objectForKey:@"custom"]objectForKey:@"m"]];
                }else
                {
                    [self.tempPmid addObject:reply];
                }
                
            }
            self.dict = @{@"tempPmid":self.tempPmid};
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"redChatPoint" object:self userInfo:self.dict];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"cellRedPoint" object:self userInfo:self.dict];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"newMessage" object:self userInfo:self.dict];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"chatlistRed" object:self userInfo:self.dict];
        }
        
        
        
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"redPicture"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"redPoint" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"allRedPoint" object:self];
        
    }
    
    //    [self.tempPmid removeAllObjects];
}
-(void)getShopContent:(HDChatProductResult*)rt
{
    if (rt.success) {
        
        [self.chatFmdbManger createTableWithPeople:[[rt.pushDic objectForKey:@"custom"]objectForKey:@"u"]];
        NSString *returnString=[rt.extends JSONString];
        //商品信息
        
        NSString * ownerAddId = [NSString stringWithFormat:@"%d",[[self.chatOBOManager arrayFromFmdbWithPmid:[[rt.pushDic objectForKey:@"custom"]objectForKey:@"u"]]count]];
        
        NSArray * dataArray = @[ownerAddId,[[rt.pushDic objectForKey:@"custom"]objectForKey:@"d"],[[rt.pushDic objectForKey:@"custom"]objectForKey:@"c"],[rt.pushDic objectForKey:@"receiver_uid"],[[rt.pushDic objectForKey:@"custom"]objectForKey:@"u"],[[rt.pushDic objectForKey:@"custom"]objectForKey:@"i"],[[rt.pushDic objectForKey:@"custom"]objectForKey:@"l"],[[rt.pushDic objectForKey:@"custom"]objectForKey:@"p"],@"0",[[rt.pushDic objectForKey:@"custom"]objectForKey:@"i"],@"0",@"3",returnString,@"",@""];
        
        
        [self.chatFmdbManger saveDataToDbPeople:dataArray People:[[rt.pushDic objectForKey:@"custom"]objectForKey:@"u"]];
    }else
    {
         [self.chatFmdbManger loadShopContent:self.productResult Extends:rt.pushDic Product:[[rt.pushDic objectForKey:@"custom"]objectForKey:@"product_id"]];
    }
}


- (void)GexinSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // [4-EXT]:发送上行消息结果反馈
    NSString *record = [NSString stringWithFormat:@"Received sendmessage:%@ result:%d", messageId, result];
    NSLog(@"record = %@",record);
    //    [_viewController logMsg:record];
}

- (void)GexinSdkDidOccurError:(NSError *)error
{
    NSLog(@"error = %@",[error localizedDescription]);
}
////////////////////**************个推***************////////////////////




#pragma mark - 上报行为记录
-(void)berichten:(NSString*)page
{
//    获取当前时间
    NSTimeInterval time = [[NSDate date]timeIntervalSince1970];
    long long int currDate = (long long int)time;
    NSString * timeStr = [NSString stringWithFormat:@"%lld",currDate];
//    取出保存时间获得保存时间与当前时间的差
    long long int savetiem  = [[[NSUserDefaults standardUserDefaults]objectForKey:@"savetime"] integerValue];
    NSDate  *datetime = [[NSDate alloc]initWithTimeIntervalSinceNow:savetiem];
    
    if (currDate - savetiem > 46800 || !savetiem) {
        
        JKHttpClient * berichten = [[JKHttpClient alloc]init];

        NSString * dataStr = [NSString stringWithFormat:@"%@|%@|firstRun|%@|%@|%@|iPhone|iPhone|%@|%@|%@|%@",page,timeStr,KEY_CHAIN_UDID,KEY_CHAIN_UDID,KEY_CHAIN_UDID,KEY_CHAIN_UDID,APP_VERSION,APPVERSIONNAM,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
        
#warning - add by SN 请注意这里是什么上报的url,以后核对一下这个url要不要改 add by SN
        NSString * berichtenUrl = [NSString stringWithFormat:@"%@dataupload/ios_traffic_analysis.php",kBaseUrl];
        [berichten post:berichtenUrl params:@{@"data": dataStr}
         result:^(JKResponse *result) {
             if (result.failure) {
                 return ;
             }
            
            [[NSUserDefaults standardUserDefaults] setObject:timeStr forKey:@"savetime"];
            [[NSUserDefaults standardUserDefaults] synchronize];
             
        }];
        //更新个人信息
        [self updateUserInfo];
        
#pragma mark - 上传崩溃日志
        NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock:^{
            [JKReporter sharedReporter];
        }];
        operation.queuePriority = NSOperationQueuePriorityVeryLow;
        NSOperationQueue * queue = [[NSOperationQueue alloc] init];
        [queue addOperation:operation];

        
        
    }
    
}




-(void)updateUserInfo
{
    NSThread * sonTread = [[NSThread alloc]initWithTarget:self selector:@selector(LoginCity) object:@"更新"];
    [sonTread start];
}

#pragma mark - UpdataUserInfo
-(void)LoginCity
{
    JKHttpClient * jkHttp = [[JKHttpClient alloc]init];
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] > 0) {
        [jkHttp get:self.uniteUrl.per_getUserInfoUrl params:@{@"fuid":[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]}
             result:^(JKResponse *result) {
                 if (result.failure) {
                     return ;
                 }
                 
                 if ([self analytic:[result objectForKey:@"user_info"] ]) {
                     //            停止线程
                 }
                 
             }];

    }
    
        [NSThread exit];
}
#pragma mark - 解析存储
-(BOOL)analytic:(NSDictionary*)request
{
    if ([self inserSQL:request]) {
        return YES;
    }else
    {
        return NO;
    }
}
#pragma mark - 插入注册/登陆完成数据
-(BOOL)inserSQL:(NSDictionary*)result
{
    sqlite3* database;
    
    sqlite3_stmt *statement;
    if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
        sqlite3_close(database);
        return NO;
    }
    
    if ([[result objectForKey:@"uid"] integerValue] - [[[NSUserDefaults standardUserDefaults]objectForKey:@"mark"]integerValue] != 0) {
        NSString * tableN = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS table_%@ (uid NUMBER PRIMARY KEY ,nickname TEXT ,face TEXT, token TEXT,gender NUMBER, uniqueId TEXT ,level NUMBER, datetime NUMBER ,authType TEXT);",[result objectForKey:@"uid"]];
        const char* create = [tableN UTF8String];
        char *errorMsg;
        if (sqlite3_exec(database, create, NULL, NULL, &errorMsg) != SQLITE_OK  ) {
            sqlite3_close(database);
            return NO;
        }

    }
    
    NSString * repStr = [NSString stringWithFormat:@"INSERT OR REPLACE INTO table_%@(uid,nickname ,face, token,gender, uniqueId ,level, datetime ,authType ) VALUES (?,?,?,?,?,?,?,?,?);",[result objectForKey:@"uid"]];
    const char* replaceStr = [repStr UTF8String];

    if (sqlite3_prepare_v2(database, replaceStr, -1, &statement, NULL) != SQLITE_OK) {
            sqlite3_close(database);
            return NO;
        }

    sqlite3_bind_int(statement, 1, [[result objectForKey:@"uid"] integerValue] ? [[result objectForKey:@"uid"] integerValue] : 1);
    NSString * nickname = [result objectForKey:@"nickname"];
    if (!(nickname && nickname.length)) {
        nickname = @"";
    }
    sqlite3_bind_text(statement, 2,[nickname UTF8String], -1, NULL);
    NSString * face = [result objectForKey:@"face"];
    if (!face || !face.length) {
        face = @"www";
    }
    sqlite3_bind_text(statement, 3, [face UTF8String], -1, NULL);
    NSString * token = [result objectForKey:@"token"];
    if (!token || !token.length) {
        token = @"";
    }
    sqlite3_bind_text(statement, 4, [token UTF8String], -1, NULL);
    sqlite3_bind_int(statement, 5, [[result objectForKey:@"gender"] ? [result objectForKey:@"gender"] : 0 integerValue]);
    NSString * uniqueID = [result objectForKey:@"uniqueID"];
    if (!uniqueID || !uniqueID.length) {
        uniqueID = @"";
    }
    sqlite3_bind_text(statement, 6, [uniqueID UTF8String], -1, NULL);
    sqlite3_bind_int(statement,7, [[result objectForKey:@"level"] integerValue] ? [[result objectForKey:@"level"] integerValue] : 0);
    sqlite3_bind_int(statement, 8, [[result objectForKey:@"datetime"] integerValue] ? [[result objectForKey:@"datetime"] integerValue] : 0);
    NSString * authType = [result objectForKey:@"authType"];
    if (!authType || !authType.length) {
        authType = @"";
    }
    sqlite3_bind_text(statement, 9, [authType UTF8String], -1, NULL);

    if (sqlite3_step(statement) != SQLITE_DONE) {
        sqlite3_close(database);
        return NO;
    }
    
   

    sqlite3_finalize(statement);
    sqlite3_close(database);
    
    return YES;
    
}



#pragma mark - 记录微信token并发送通知
-(void)onResp:(BaseResp*)resp
{
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp* temp = (SendAuthResp*)resp;
        
        NSString* strJson = [self getAppid:WX_APP_ID AndSecret:WX_APP_SECRECT AndTempCode:temp.code];
        NSData* jsonData = [strJson dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary* result = [jsonData objectFromJSONData];
        NSString* refreshToken = [result objectForKey:@"refresh_token"];
        
        NSString* refreshUrl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%@&grant_type=refresh_token&refresh_token=%@",WX_APP_ID,refreshToken];
        NSURL* refresh = [NSURL URLWithString:refreshUrl];
        NSURLRequest* refreshRequset = [[NSURLRequest alloc]initWithURL:refresh cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        NSData* refreshData = [NSURLConnection sendSynchronousRequest:refreshRequset returningResponse:nil error:nil];
        NSString* refreshString = [[NSString alloc]initWithData:refreshData encoding:NSUTF8StringEncoding];
        NSData* reData = [refreshString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary* refreshDic = [reData objectFromJSONData];
        
        //        检验token是否有效
        NSString* string = [self checkToke:[result objectForKey:@"access_token"] AndOpenid:[result objectForKey:@"openid"]];
        NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary* checkDic = [data objectFromJSONData];
        NSString* errormsg = [checkDic objectForKey:@"errmsg"];
      
        NSString * wx_access_token = [NSString stringWithFormat:@"%@",[refreshDic objectForKey:@"access_token"]];
        NSString * wx_openid = [NSString stringWithFormat:@"%@",[result objectForKey:@"openid"]];
        
        [[NSUserDefaults standardUserDefaults]setObject:wx_access_token forKey:@"access_token"];
        [[NSUserDefaults standardUserDefaults]setObject:wx_openid forKey:@"openid"];
        [[NSUserDefaults standardUserDefaults]synchronize];

        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"access_token"] isEqualToString:@"(null)"] ) {
             [[NSNotificationCenter defaultCenter] postNotificationName:@"loginOut" object:self];
        }else
        {
         [[NSNotificationCenter defaultCenter] postNotificationName:@"login" object:self];
        }
       
    } else if ([resp isKindOfClass:[PayResp class]]) {
#pragma mark - 微信支付的返回
        DLog(@"微信支付");
        PayResp *response = (PayResp *)resp;
        
        if (response.errCode == WXSuccess) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WXPayResultNotification" object:nil];
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WXPayResultNotification" object:response];
        }
    }
    
}


#pragma mark - GPS
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([self.location respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [self.location requestWhenInUseAuthorization];
            }
            break;
            
        default:
            break;
    }
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation * currLocation = [locations lastObject];
    NSString * lat = [NSString stringWithFormat:@"%f",currLocation.coordinate.latitude];
    NSString * lng = [NSString stringWithFormat:@"%f",currLocation.coordinate.longitude];

    [[NSUserDefaults standardUserDefaults] setObject:lat forKey:@"lat"];
    [[NSUserDefaults standardUserDefaults] setObject:lng forKey:@"lng"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.location stopUpdatingLocation];
}

#pragma mark - url
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [TencentOAuth HandleOpenURL:url] || [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
#pragma mark - 支付宝回调 handleOpenURL  by  王少宁
    [self zfbPayResultWithUrl:url application:application];
    
    return [TencentOAuth HandleOpenURL:url] || [WXApi handleOpenURL:url delegate:self];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // [EXT] 切后台关闭SDK，让SDK第一时间断线，让个推先用APN推送
    self.state = NO;
    state = 1;
    [self stopSdk];

    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
//    NSLog(@"ForeGround");
    [self berichten: @"HDAppDelegate"];
    
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"linglingID"]length] > 0) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"refreshErcode" object:nil];
    }
    
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
//    上报行为记录
//    NSLog(@"Active");
    // [EXT] 重新上线
    
    [self startSdkWith:GT_APP_ID appKey:GT_APP_KEY appSecret:GT_APP_SECRET];

}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}
//
//-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
//{
//    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
//    _deviceToken = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
//    NSLog(@"deviceToken:%@", _deviceToken);
//    
//    // [3]:向个推服务器注册deviceToken
//    if (_gexinPusher) {
//        [_gexinPusher registerDeviceToken:_deviceToken];
//    }
//}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    // [ GTSdk ]：向个推服务器注册deviceToken
    [_gexinPusher registerDeviceToken:token];
}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error
{
    // [3-EXT]:如果APNS注册失败，通知个推服务器
    if (_gexinPusher) {
        [_gexinPusher registerDeviceToken:@""];
    }
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    
    
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 9;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    NSLog(@"%@-----%@",[[userInfo objectForKey:@"payload"] class],userInfo);
    NSString * payload = [userInfo objectForKey:@"payload"];
    NSData *jsonData = [payload dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * pushDic = [jsonData objectFromJSONData];
    NSString *payloadMsg = [NSString stringWithFormat:@"%@",[pushDic objectForKey:@"messageid"] ];
    self.noticId = payloadMsg;
   //睡眠2秒
    sleep(1);
    
    if (self.state == NO) {
        
        self.state = YES;
        
        if ([[pushDic objectForKey:@"tp"]integerValue] == 10) {
            //跳转系统详情
            [[NSNotificationCenter defaultCenter] postNotificationName:@"System" object:self userInfo:pushDic];
            
            
//            if ([[pushDic objectForKey:@"type"]integerValue] == 1) {
//                //跳转系统详情
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"System" object:self userInfo:pushDic];
//            }else if ([[pushDic objectForKey:@"type"]integerValue] == 3){
//                //跳转活动列表
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"Activity" object:self userInfo:pushDic];
//                
//            }else if ([[pushDic objectForKey:@"type"]integerValue] == 4){
//                //跳转商品详情
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"Card" object:self userInfo:pushDic];
//                
//            }else if ([[pushDic objectForKey:@"type"]integerValue] == 2){
//                //跳转到web
//                [[NSNotificationCenter defaultCenter] postNotificationName:@"PresentView" object:self userInfo:pushDic];
//            }
            
        }
        else if([[pushDic objectForKey:@"tp"]integerValue] == 12)
        {
            //跳转回复详情页
            //        NSMutableArray * arr = [NSMutableArray array];
            //        [arr addObject:[pushDic objectForKey:@"pmid"] ];
            
            if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] > 0) {
                NSString * reply = [NSString stringWithFormat:@"reply%@",[pushDic objectForKey:@"sender_uid"]];
                NSMutableArray * arr = [NSMutableArray arrayWithObjects:reply, nil];
                NSDictionary * dic = @{@"pmid":arr};
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatList" object:self userInfo:dic];
            }
            
            
        } else if([[pushDic objectForKey:@"tp"]integerValue] == 20){
            //跳转聊天详情页
            
            if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] > 0) {
                NSMutableArray * arr = [NSMutableArray array];
                [arr addObject:[pushDic objectForKey:@"pmid"] ];
                NSDictionary * dic = @{@"pmid":arr};
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatList" object:self userInfo:dic];
            }
            
           
            
            

            
        }
        else if ([[pushDic objectForKey:@"tp"]integerValue] == 15){
        
            //跳转到web
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PresentView" object:self userInfo:pushDic];
        
        }
        
    }
    
    
    
    
    self.pushInfo = userInfo;
    [self.pushInfoArray addObject:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark 分析推送的消息
- (void)analysisRemoteNotification:(NSDictionary *)userInfo{
    
    NSString * payload = [userInfo objectForKey:@"payload"];
    NSData *jsonData = [payload dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * pushDic = [jsonData objectFromJSONData];
    
    
    if ([[pushDic objectForKey:@"tp"]integerValue] == 10) {
        
        if (pushDic != nil) {
            
            [[NSUserDefaults standardUserDefaults] setObject:@"temaidata" forKey:@"kRemoteNotificationUserInfoType"];
//            [[NSUserDefaults standardUserDefaults] setObject:pushDic forKey:@"kRemoteNotificationUserInfoData"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }
        
        

      /*
        if ([[pushDic objectForKey:@"type"]integerValue] == 4) {
            //跳转商品详情
            [[NSUserDefaults standardUserDefaults] setObject:@"carddata" forKey:@"kRemoteNotificationUserInfoType"];
            [[NSUserDefaults standardUserDefaults] setObject:pushDic forKey:@"kRemoteNotificationUserInfoData"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else if ([[pushDic objectForKey:@"type"]integerValue] == 3){
            //跳转活动列表
            [[NSUserDefaults standardUserDefaults] setObject:@"activitydata" forKey:@"kRemoteNotificationUserInfoType"];
            [[NSUserDefaults standardUserDefaults] setObject:pushDic forKey:@"kRemoteNotificationUserInfoData"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }else if ([[pushDic objectForKey:@"type"]integerValue] == 1){
            //跳转特卖列表
            [[NSUserDefaults standardUserDefaults] setObject:@"temaidata" forKey:@"kRemoteNotificationUserInfoType"];
            [[NSUserDefaults standardUserDefaults] setObject:pushDic forKey:@"kRemoteNotificationUserInfoData"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }else if ([[pushDic objectForKey:@"type"]integerValue] == 2){
            //跳转到web
            [[NSUserDefaults standardUserDefaults] setObject:@"webdata" forKey:@"kRemoteNotificationUserInfoType"];
            [[NSUserDefaults standardUserDefaults] setObject:pushDic forKey:@"kRemoteNotificationUserInfoData"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
      */
    }
    else if([[pushDic objectForKey:@"tp"]integerValue] == 12)
    {
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] > 0) {
            
            NSString * reply = [NSString stringWithFormat:@"reply%@",[pushDic objectForKey:@"sender_uid"]];
            NSMutableArray * arr = [NSMutableArray arrayWithObjects:reply, nil];
            NSDictionary * dic = @{@"pmid":arr};
            
            [[NSUserDefaults standardUserDefaults] setObject:@"chatlistdata" forKey:@"kRemoteNotificationUserInfoType"];
            [[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"kRemoteNotificationUserInfoData"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        }
        
       
        
        
        
        
    } else if([[pushDic objectForKey:@"tp"]integerValue] == 20){
        //跳转聊天详情页
        
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue] > 0) {

            NSMutableArray * arr = [NSMutableArray array];
            [arr addObject:[pushDic objectForKey:@"pmid"] ];
            NSDictionary * dic = @{@"pmid":arr};
            
            [[NSUserDefaults standardUserDefaults] setObject:@"chatlistdata" forKey:@"kRemoteNotificationUserInfoType"];
            [[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"kRemoteNotificationUserInfoData"];
            [[NSUserDefaults standardUserDefaults] synchronize];        }

    }
    else if ([[pushDic objectForKey:@"tp"]integerValue] == 15){
    
        //跳转到web
        [[NSUserDefaults standardUserDefaults] setObject:@"webdata" forKey:@"kRemoteNotificationUserInfoType"];
        [[NSUserDefaults standardUserDefaults] setObject:pushDic forKey:@"kRemoteNotificationUserInfoData"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    
    }
    
    
    self.pushInfo = userInfo;
    [self.pushInfoArray addObject:userInfo];
    
}



- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 

            abort();
        } 
    }
}

#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"healthyexpert" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"healthyexpert.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */

        abort();
    }    
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


#pragma mark - 获取微信token
-(NSString*)getAppid:(NSString*)Appid AndSecret:(NSString*)Secret AndTempCode:(NSString*)code
{
    NSString* urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WX_APP_ID,WX_APP_SECRECT,code];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *strJson = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
    return strJson;
}
#pragma mark - 检验微信token是否有效
-(NSString*)checkToke:(NSString*)token AndOpenid:(NSString*)openid
{
    NSString* checkUrl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/auth?access_token=%@&openid=%@",token,openid];
    NSURL* check = [NSURL URLWithString:checkUrl];
    NSURLRequest* checkRequset = [[NSURLRequest alloc]initWithURL:check cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSData* checkData = [NSURLConnection sendSynchronousRequest:checkRequset returningResponse:nil error:nil];
    NSString* checkString = [[NSString alloc]initWithData:checkData encoding:NSUTF8StringEncoding];
    
    return checkString;
}




#pragma mark - 获取md5加密
-(NSString*)MD5:(NSString*)str
{
    const char *xcStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(xcStr, strlen(xcStr), result);
    
    return[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
           result[0], result[1], result[2], result[3],
           result[4], result[5], result[6], result[7],
           result[8], result[9], result[10], result[11],
           result[12], result[13], result[14], result[15]
           ];
    
}
#pragma mark -获取数据库文件路径
-(NSString*)dataFilePath
{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString* documentDirectroy = [paths objectAtIndex:0];
    NSString* fileName = [documentDirectroy stringByAppendingPathComponent:kDatabaseName];
    return fileName;
}
//#pragma mark - 载入数据库
//-(void)loadSqlite
//{
//    
//    NSString* path = [self dataFilePath];
//    if (sqlite3_open([path UTF8String], &_database) != SQLITE_OK) {
//        
//        UIAlertView* av = [[UIAlertView alloc]initWithTitle:@"警告" message:@"创建数据库失败" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
//        [av show];
//        
//        sqlite3_close( _database);
//        
//    }
//    else
//    {
//        
//    }
//    
//}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView isKindOfClass:SNPleaseLogInAlertView.class]){
        [((SNPleaseLogInAlertView *)alertView) afterLoginBtnClicked];
    }
}


//支付宝回调 by 王少宁
//独立客户端回调函数
- (void)zfbPayResultWithUrl:(NSURL *)url application:(UIApplication *)application {
    
    //如果极简开发包不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给开 发包
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ZFBPayResultNotification" object:resultDic];
        }]; }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ZFBPayResultNotification" object:resultDic];
        }];
    }
    
}

#pragma mark - 绑定uid & cid
-(void)uploadUidAndCid
{
    NSString* urlStr = [NSString stringWithFormat:@"%@?clientid=%@&uid=%@",self.uniteUrl.per_upLoadGePushIdUrl,_clientId,[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
    DLog(@"%@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *strJson = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
}

#pragma mark - 显示表情键盘
- (void) showEmojiKeyboard {
    if (self.emojiKeyboard == nil ) {
        [self setupEmojiKeyboard];
    }
    else{
        [self.emojiKeyboard tilePages];
    }
    BOOL isSubView = (_emojiKeyboard.superview==ApplicationDelegate.window);
    if (!isSubView) {
        [ApplicationDelegate.window addSubview:self.emojiKeyboard];
    }
    
    self.emojiKeyboard.hidden = NO;
    
    [UIView beginAnimations:@"showEmojiKeyboard" context:NULL];
    [UIView setAnimationDuration:0.25f];
    UIImage *bgImage = [UIImage imageNamed:@"LMBang_emojiView_BG.png"];
    self.emojiKeyboard.frame = CGRectMake(0.0f, ApplicationDelegate.window.frame.size.height - bgImage.size.height, [[UIScreen mainScreen] applicationFrame].size.width, bgImage.size.height);
    [UIView commitAnimations];
    
}

#pragma mark - 隐藏表情键盘：
- (void) hideEmojiKeyboard {
    [UIView beginAnimations:@"hideEmojiKeyboard" context:NULL];
    [UIView setAnimationDuration:0.15f];
    [UIView setAnimationDelegate: self];
    [UIView setAnimationDidStopSelector: @selector(hieEmojiKyeboardAnimationStopped:finished:context:)];
    CGRectSetY(_emojiKeyboard, ApplicationDelegate.window.frame.size.height);
    [UIView commitAnimations];
    self.emojiKeyboard.hidden = YES;
}

#pragma mark - 创建表情键盘：
- (void) setupEmojiKeyboard {
    LMBangEmojiView *emojiView = [[LMBangEmojiView alloc] init];
    [self setEmojiKeyboard:emojiView];
}

#pragma mark - 加载表情到内存
- (void) setupEmojiToMemory {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"ios6EmojiList_990" ofType:@"plist"];
    NSArray *emojis = [NSArray arrayWithContentsOfFile:path];
    if (emojis && [emojis count] > 0) {
        self.emojiStrings = emojis;
    }
}


@end
